<template>
	<Layout desc="https://petswitch.com/">
		<div class="image-container">
			<div class="image-section">
				<h3>人物图片</h3>
				<img id="human" src="./mock/human.jpeg" alt="人物图片" />
			</div>
			<div class="image-section">
				<h3>动物图片</h3>
				<img id="pet" :src="petImageSrc" alt="动物图片" />
			</div>

			<div class="image-section">
				<h3>换脸结果</h3>
				<canvas ref="resultCanvas"></canvas>
			</div>
		</div>
	</Layout>
</template>

<script setup>
import helpers from './core/helpers.js'
import constants from './core/constants.js'
import preloadImages from './core/preload-images.js'
import extractHumanFeatures from './core/extract-human-features.js'
import renderPetswitch from './core/render-petswitch.js'

import humanLandmarks from './mock/HumanFaceLandmarks.json'
import { presets, images } from './preset'

const presetNames = Object.keys(presets)

const activePet = ref(presetNames[8])

const petImageSrc = computed(() => {
	return images[activePet.value] || ''
})

const resultCanvas = ref(null)

const uiImageElements = ref({})

preloadImages.then((images) => {
	images.forEach((image) => {
		uiImageElements.value[image.id] = image
	})
})

const genCanvas = (image) => {
	let canvas = document.createElement('canvas')
	let ctx = canvas.getContext('2d')

	let resized = helpers.calculateAspectRatioFit(
		image.width,
		image.height,
		constants.MAX_WIDTH,
		constants.MAX_HEIGHT
	)

	canvas.width = resized.width
	canvas.height = resized.height

	// 绘制图片到画布
	ctx.drawImage(image, 0, 0, resized.width, resized.height)

	return canvas
}

onMounted(() => {
	const petImage = document.getElementById('pet')
	const humanImage = document.getElementById('human')

	let imagesLoaded = 0
	const totalImages = 2

	const onImageLoad = () => {
		imagesLoaded++
		if (imagesLoaded === totalImages) {
			executePetSwitch(petImage, humanImage)
		}
	}
	petImage.addEventListener('load', onImageLoad)
	humanImage.addEventListener('load', onImageLoad)
})

const executePetSwitch = (petImage, humanImage) => {
	const petCanvas = genCanvas(petImage)
	const humanCanvas = genCanvas(humanImage)

	const outputCanvas = resultCanvas.value
	outputCanvas.width = petCanvas.width
	outputCanvas.height = petCanvas.height

	extractHumanFeatures.beginRender(
		humanLandmarks,
		humanCanvas,
		uiImageElements.value,
		(humanFeatures) => {
			renderPetswitch.outputFinalImage(
				humanFeatures,
				outputCanvas,
				petCanvas,
				presets[activePet.value]
			)
		}
	)
}
</script>

<style scoped lang="scss">
.image-container {
	display: flex;
	gap: 20px;
	justify-content: center;
	flex-wrap: wrap;
}

canvas,
.image-section img {
	max-width: 100%;
	max-height: 300px;
	border: 2px solid #e0e0e0;
	border-radius: 8px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>
